package com.xy.tool.webmvc.interceptor;

import com.xy.biz.uc.domain.bo.ResourceBO;
import com.xy.biz.uc.domain.bo.UserBO;
import com.xy.biz.uc.domain.enums.ResourceEnum;
import com.xy.biz.uc.domain.query.UserIdQuery;
import com.xy.biz.uc.manager.UserManager;
import com.xy.tool.context.UserContextHolder;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author wwj
 * @Date 2021/6/3
 */
public class TeamManagementInterceptor extends HandlerInterceptorAdapter {

    private UserManager userManager;

    public TeamManagementInterceptor(UserManager userManager) {
        this.userManager = userManager;
    }

    public TeamManagementInterceptor() {
    }

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        if("OPTIONS".equals(request.getMethod())) {
            return true;
        }
        Long userId = UserContextHolder.getUserId();
        UserBO user = userManager.getUser(UserIdQuery.builder().userIdList(Arrays.asList(userId))
                .withRole(true)
                .withResource(true)
                .build());
        Set<Long> resourceIdSet = user.getResourceBOSet().stream().map(ResourceBO::getResourceId).collect(Collectors.toSet());

        if (resourceIdSet.contains(ResourceEnum.TEAM_MANAGEMENT.getCode())) {
            return true;
        }
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }
}
